package com.junko.api.configuration;

import com.junko.api.interceptor.ApiInterceptor;
import com.junko.api.interceptor.ErrorPageHandler;
import com.junko.api.interceptor.NeedUserTokenInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {

    @Value("${web.upload-path}")
    private String baseUploadPath;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(apiInterceptor()).addPathPatterns("/api/**");
        registry.addInterceptor(needTokenInterceptor()).addPathPatterns("/api/**");
        registry.addInterceptor(errorPageHandler()).addPathPatterns("/api/**");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .allowedHeaders("access_token","user_token","Content-Type","System","X-Requested-With")
                .maxAge(3600);
    }

    @Bean
    public NeedUserTokenInterceptor needTokenInterceptor(){
        return new NeedUserTokenInterceptor();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/upload/**").addResourceLocations("file:"+ baseUploadPath);
    }

    @Bean
    public ErrorPageHandler errorPageHandler(){
        return new ErrorPageHandler();
    }
    @Bean
    public ApiInterceptor apiInterceptor(){
        return new ApiInterceptor();
    }
}